import utils from "core/utils/utils";
import { TimerModel, TimerTaskModel } from "core/model/timerModel";

let timerHandleID = 1
const timeInterval = 16//设置计时器步长 100毫秒
export default class TimerHandle {
    timerInfo: TimerModel
    perTime: number
    gameTimer: any = {}
    timeCoe: number
    timerHandleID: number
    currentTime: number
    pauseTime: number
    testAmount: number = 0
    testnumber: number = 0
    timeInterval: number = timeInterval
    totalRunTime: number = 0
    constructor() {
        this.timerInfo = new TimerModel({})
        this.timeCoe = 1
        this.timerHandleID = timerHandleID++
    }
    async start() {
        let timerInfo = this.timerInfo
        timerInfo.state = 1//计时器开关   值为1的时候打开
        this.perTime = (performance || Date).now()
        let intervalTime = 0
        let pauseintervalTime = 0
        this.currentTime = (performance || Date).now()
        let times = 0
        while ((timerInfo.state == 1 || timerInfo.state == 3) && times < 500000) {
            if (this.timeCoe == 0) {
                intervalTime += timeInterval
            } else {
                let nowTime = (performance || Date).now()
                let _timeInterval = nowTime - this.perTime
                if (_timeInterval >= timeInterval * 100) {
                    _timeInterval = timeInterval
                }
                if (timerInfo.state == 1) {
                    intervalTime += _timeInterval * this.timeCoe
                }
                this.perTime = (performance || Date).now()
            }
            let timeCount = timerInfo.timeCount
            if (timerInfo.state == 1 && timeCount * timeInterval <= intervalTime) {
                let timeQueueItems = timerInfo.timeQueue[timeCount]
                //遍历时间点上的计时器任务
                if (timeQueueItems) {
                    for (let i = 0; i < timeQueueItems.length; i++) {
                        let task: TimerTaskModel = timeQueueItems[i]
                        //判断任务是否开启
                        if (task.disable == false && timerInfo.state == 1) {
                            await task.fn()
                            if (task.count == 0) {
                                this.setInterval(task.fn, task.interval)
                            }
                        }
                    }
                    //释放数据
                    delete timerInfo.timeQueue[timeCount]
                }
                timerInfo.timeCount += 1
            } else {
                await this.sleep(timeInterval)//等待一个计时器步长时间
                this.totalRunTime += timeInterval
            }
            if (timerInfo.state == 1) {
                times += 1
            }
        }
    }

    sleep(timeout: number, cb?: (number) => void): Promise<any> {
        return new Promise(async resolve => {
            let timerID: any = setTimeout(() => {
                delete this.gameTimer[timerID]
                resolve(timerID)
            }, timeout);
            this.gameTimer[timerID] = timerID
            cb && cb(timerID)
        })
    }
    getTime() {
        let timerInfo = this.timerInfo
        let timeCount = timerInfo.timeCount
        return timeInterval * timeCount
    }

    getTimerEndTime(id) {
        let timerInfo = this.timerInfo
        let item: TimerTaskModel = timerInfo.timeQueueObject[id]
        return timeInterval * item.time
    }

    setTimeout(fn: any, interval: number | any) {
        let intervalValue
        if (typeof interval == 'number') {
            intervalValue = interval
        } else if (typeof interval == 'function') {
            intervalValue = interval()
        }

        let timerInfo = this.timerInfo
        let timeCount = timerInfo.timeCount
        let endTimeCount = Math.floor(timeCount + intervalValue / timeInterval)
        if (endTimeCount < 1) {
            endTimeCount = 1
        }
        let timeQueueItems = timerInfo.timeQueue[endTimeCount]
        if (!timeQueueItems) {
            timerInfo.timeQueue[endTimeCount] = []
            timeQueueItems = timerInfo.timeQueue[endTimeCount]
        }
        let taskItem = new TimerTaskModel()
        taskItem.id = timerInfo.taskAutoID++
        taskItem.fn = fn
        taskItem.count = 1
        taskItem.interval = interval
        taskItem.time = endTimeCount
        timeQueueItems.push(taskItem)
        timerInfo.timeQueueObject[taskItem.id] = taskItem
        return taskItem.id
    }

    //设置间隔
    setInterval(fn: any, interval: number | any) {
        let intervalValue//毫秒时间
        if (typeof interval == 'number') {
            intervalValue = interval
        } else if (typeof interval == 'function') {
            intervalValue = interval()
        }

        let timerInfo = this.timerInfo
        let timeCount = timerInfo.timeCount
        let endTimeCount = Math.floor(timeCount + intervalValue / timeInterval)
        if (endTimeCount < 1) {
            endTimeCount = 1
        }
        let timeQueueItems = timerInfo.timeQueue[endTimeCount]
        if (!timeQueueItems) {
            timerInfo.timeQueue[endTimeCount] = []
            timeQueueItems = timerInfo.timeQueue[endTimeCount]
        }
        let taskItem = new TimerTaskModel()
        taskItem.id = timerInfo.taskAutoID++
        taskItem.fn = fn
        taskItem.count = 0
        taskItem.interval = interval
        taskItem.time = endTimeCount
        timeQueueItems.push(taskItem)
        timerInfo.timeQueueObject[taskItem.id] = taskItem
        return taskItem.id
    }


    clearTimeout(id) {
        let timerInfo = this.timerInfo
        let item = timerInfo.timeQueueObject[id]
        if (item) {
            item.disable = true
        }
    }

    // addTimeCount(timeId: number, interval: number){
    //     let timerInfo = this.timerInfo
    //     let taskItem = timerInfo.timeQueueObject[timeId]

    //     let endTimeCount = Math.floor(taskItem.time - interval / timeInterval)
    //     taskItem.time = endTimeCount
    // }

    stop() {
        this.timerInfo.state = 2
    }
    pause() {
        this.timerInfo.state = 3
        this.pauseTime = (performance || Date).now()
    }
    contine() {
        this.timerInfo.state = 1
    }
}